/*
 * Copyright 2010 Biz-e (info@biz-e.nl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.biz_e.appengine.lib.server.objectify;

import nl.biz_e.appengine.lib.shared.objectify.IEntity;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Query;

/**
 * Some static utility methods for working with the <a
 * href="http://code.google.com/p/objectify-appengine/">Objectify</a> library.
 * 
 * @author Joost A. Bloemsma
 */
public class ObjectifyUtils {

    /**
     * Constructs a new ObjectifyUtils instance.<br/>
     * Declared private to make sure it will never be instatiated.
     */
    private ObjectifyUtils() {
        super();
    }

    /**
     * Returns a single result from a query. Null if the query contains no
     * results.
     * 
     * @param <T>
     *            Type of the resulting object
     * @param query
     *            The {@link Query} itself
     * @return The result casted to type <T>
     * @throws IllegalArgumentException
     *             If the query results in more than one result.
     */
    public static <T> T getResultSingle(Query<T> query) {
        if (query.countAll() == 0)
            return null;
        if (query.countAll() > 1)
            throw new IllegalArgumentException("Too many results in query");
        return query.get();
    }

    /**
     * @param <E>
     *            The type of Key to be returned.
     * @param entity
     * @return A {@link Key} identifying the passed entity
     */
    @SuppressWarnings("unchecked")
    public static <E extends IEntity> Key<E> generateKey(E entity) {
        return new Key<E>((Class<? extends E>) entity.getClass(), entity
                .getId());
    }
}
